//
//  NetWorkManager.m
//  Go!
//
//  Created by rimi on 16/7/7.
//  Copyright © 2016年 凌风. All rights reserved.
//

#import "NetWorkManager.h"
#import "AFNetworking/AFNetworking.h"
#import "XMLDictionary.h"

@implementation NetWorkManager

//关于网络请求需要的参数说明
//portUrl:问号前面的到斜杠的的接口
//urlParam:参数
//直接返回JOSN数据类型


+ (void)getWithURL:(NSString *)portUrl
       urlParam:(NSDictionary *)urlParam
      successBlock:(Success)successblock
      FailureBlock:(Failure)failureblock{
    NSInteger networkType = [self checkNetWork];
    if (networkType == 0) {
        [Tools showAlertWithMessage:@"网络连接失败,请检查网络"];
    }
    else {
        //拼接主网址
        NSString *httpUrl = @"http://apis.baidu.com/baidunuomi/openapi/";
        httpUrl = [httpUrl stringByAppendingString:[NSString stringWithFormat:@"%@?",portUrl]];
        
        /*< 使用AFNetworking做网络请求 **/
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",  nil];
        [manager.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];
        
        if (urlParam == nil) {
            [manager GET:httpUrl parameters:@"" progress:^(NSProgress * _Nonnull downloadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (successblock) {
                    successblock(responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"%@",error);
            }];
            return;
        }
        
        [manager.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];
        [manager GET:httpUrl parameters:urlParam progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (successblock) {
                successblock(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
    }
     
}

#pragma mark - 网络判断
+ (NSInteger)checkNetWork {
    // 状态栏是由当前控制器控制的，首先获取当前app。
    UIApplication *app = [UIApplication sharedApplication];
    
    // 遍历状态栏上的前景视图
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    
    
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    // type数字对应的网络状态依次是：0：无网络；1：2G网络；2：3G网络；3：4G网络；5：WIFI信号
    //    NSLog(@"type is '%d'.", type);
    return type;
}

@end
